package com.jgsu.farm.service.impl;

import com.jgsu.farm.entity.Model;
import com.jgsu.farm.entity.User;
import com.jgsu.farm.exception.DataAddException;
import com.jgsu.farm.exception.DataNotExistException;
import com.jgsu.farm.mapper.ModelMapper;
import com.jgsu.farm.mapper.UserMapper;
import com.jgsu.farm.mapper.sql.ModelMapperSql;
import com.jgsu.farm.service.ModelService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class ModelServiceImpl implements ModelService {
    @Autowired
    ModelMapperSql modelMapperSql;
    @Autowired
    UserMapper userMapper;
    @Autowired
    ModelMapper modelMapper;


    @Override
    public void add(Model model) {
        User user = userMapper.selectByPrimaryKey(model.getAuthor());
        if (user == null) {
            throw new DataAddException("604", "用户id不存在");
        } else {
            modelMapper.insert(model);
        }
    }

    @Override
    public void delete(Integer modelid) {
        Integer modelId = modelMapper.deleteByPrimaryKey(modelid);
        if (modelId == 0 || modelId == null) {
            throw new DataNotExistException("603", "不存在该id,诊断模型删除失败");
        }
    }

    @Override
    public PageInfo<Model> selectAll(int page, int pagesize) {
        PageHelper.startPage(page, pagesize);
        List<Model> models = modelMapper.selectAll();
        PageInfo<Model> pageInfoModelList = new PageInfo<>(models);
        return pageInfoModelList;
    }

    @Override
    public void update(Model model) {
        Model modelId = modelMapper.selectByPrimaryKey(model.getModelid());
        User userId = userMapper.selectByPrimaryKey(model.getAuthor());
        if (modelId == null || userId == null) {
            throw new DataNotExistException("604", "数据更新失败，模型id或用户id不存在");
        } else {
            modelMapper.updateByPrimaryKey(model);
        }
    }

}
